package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * @Classname DownController
 * @Description TODO
 * @Date 2021/7/3 22:00
 * @Created by 17976
 */
@Controller
@RequestMapping("/hello")
public class DownController {
    @RequestMapping("/downLoad")
    public void downLoad(HttpServletResponse response, HttpServletRequest request) throws IOException {
        FileInputStream inputStream = new FileInputStream("D:\\软件安装包\\SunloginClient_11.1.2.38529_x64.exe");
        response.reset();
        response.setContentType("bin");
        String agent = request.getHeader("User-Agent");
        String fileName = "fileName";
        if (agent.contains("MSIE") || agent.contains("Trident")) {
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
        } else {
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        }
        response.addHeader("Content-Disposition","attachment; filename=\"" + fileName + "\"");
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(bytes))>0) {
            response.getOutputStream().write(bytes,0,len);
        }
        inputStream.close();
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }
}
